/*
 * Copyright (C), 2002-2018, 你的兔宝宝电子商务有限公司
 * FileName: NetServiceImpl.java
 * Author:   你的兔宝宝
 * Date:     2018-2-23 下午2:42:50
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.baby.demo.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baby.demo.service.NetService;
import com.baby.demo.utils.FileUtil;
import com.baby.demo.utils.Files;
import com.baby.demo.utils.Strings;
import com.baby.demo.utils.net.CURL;

/**
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 你的兔宝宝
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class NetServiceImpl implements NetService{
    
    private static final Logger logger = LoggerFactory.getLogger(NetService.class);
    
    /**
     * 
     * 功能描述: 下载资源文件<br>
     * 〈功能详细描述〉
     *
     * @param localpath
     * @param localroot
     * @param resource
     * @param curl
     * @return
     * @throws Exception 
     * @Author:   你的兔宝宝
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String downloadResource(String localroot,String localpath,String resourceroot,String resource,CURL curl){
        String resourceLocation = resourceroot + resource;
        if( resource.startsWith("http") || resource.startsWith("//") ){
            resourceLocation = resource;
        }
        Map<String,String> fileobj = Files.getFileInfo(resourceLocation);
        String fileName = Strings.get(fileobj, "fileName");
        String suffix = Strings.get(fileobj, "suffix");
        System.out.println(resourceLocation);
        System.out.println(localpath+fileName);
        
        //图片读流
        if(Files.allowExts(fileName, "svg|jpg|jpeg|png|gif")){
            curl.curl(resourceLocation,localpath+fileName);
        }else{//js、css读文本
            String stream = curl.curl(resourceLocation);
            //css资源处理
            if("css".equalsIgnoreCase(suffix)){
                String path = Strings.get(fileobj, "path");
                stream = downloadCssResource(localroot,stream,path,curl);
            }
            FileUtil.writeFile(localpath+fileName,stream);
        }
        return fileName;
    }
    
    /**
     * 
     * 功能描述: 下载css样式涉及到的资源<br>
     * 〈功能详细描述〉
     *
     * @param localpath
     * @param stream
     * @param localroot
     * @param curl
     * @return
     * @Author:   你的兔宝宝
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String downloadCssResource(final String localroot,String stream,final String resourceroot,final CURL curl){
        String[] regexs = new String[]{
                "@import\\s*url\\(\"(?<url>[^\"]+?)\"\\)",
                "url\\((\"|')?(?<url>[^\"'\\)]+?)(\"|')?\\)"
        };
        final String[] dirs = new String[]{"css/","css/images/"};
        final String[] replaceDirs = new String[]{"","images/"};
        String stream1 = Strings.replaceTxt(stream, regexs, "url",new Strings.LineCallback(){
            @Override
            public String replace(String line, String target,int regexat) {
                String dir = dirs[regexat];
                String replaceDir = replaceDirs[regexat];
                String resourceLocation = resourceroot+target;
                if( target.startsWith("http") || target.startsWith("//") ){
                    resourceLocation = target;
                }
                Map<String,String> fileobj = Files.getFileInfo(resourceLocation);
                String fileName = Strings.get(fileobj, "fileName").replaceAll(":|\\?", "-");
                if(!fileName.endsWith(".css") && regexat==0){
                    fileName +=".css";
                }
                if(Files.allowExts(fileName, "eot|woff|ttf")){
                    dir = "fonts/";
                    replaceDir = "../fonts/";
                }
                String localLocation = localroot+dir; 
                if(fileName.endsWith(".css")){
                    String stream2 = curl.curl(resourceLocation);
                    stream2 = downloadCssResource(localroot,stream2,resourceroot,curl);
                    FileUtil.writeFile(localLocation+fileName,stream2);
                }else{
                    try {
                        curl.curl(resourceLocation,localLocation+fileName);
                    } catch (Exception e) {
                        logger.error("下载自营异常{},error:{}",new Object[]{resourceLocation,e.getMessage()});
                    }
                }
                System.out.println(resourceLocation);
                System.out.println(localLocation+fileName);
                return line.replace(target, replaceDir+fileName);
            }
        });
        return stream1;
    }
    
    @Override
    public void downloadJqDemo(Map<String, Object> params){
        String url = Strings.get(params, "url");
        String filepath = "E:\\js-project\\ui\\";
        
        final CURL curl = new CURL();
        curl.proxy("10.19.110.55", "8080");
        final String resourceroot = Strings.get(params, "resourceroot",url);
        final String filename = Strings.get(params, "filename",url.substring(url.indexOf("demo/")+5));
        final String localroot = filepath+filename;
        String stream = curl.curl(url);
        String[] regexs = new String[]{
                ".*?<link.*?href=(\"|')(?<url>[^\"']+?)(\"|').*?>.*",
                ".*?<script.*?src=(\"|')(?<url>[^\"']+?)(\"|').*?></script>.*", 
                ".*?<img.*?src=(\"|')(?<url>[^\"']+?)(\"|').*?>.*"
        };
        final String[] dirs = new String[]{"css/","js/","images/"};
        stream = Strings.replaceTxt(stream, regexs, "url",new Strings.LineCallback(){
            @Override
            public String replace(String line, String target,int regexat){
                //System.out.println(target);
                String dir = dirs[regexat];
                String name = downloadResource(localroot,localroot+dir,resourceroot,target,curl);
                return line.replace(target, dir+name);
            }
        });
        //System.out.println(stream);
        String indexfile = filepath+filename+filename.substring(0,filename.length()-1)+".html";
        System.out.println(indexfile);
        FileUtil.writeFile(indexfile,stream);
        
    }

    @Override
    public void downloadJqDemoResource(Map<String, Object> params) throws Exception {
        String url = Strings.get(params, "url");
        String resource = Strings.get(params, "resource");
        String filepath = "E:\\js-project\\ui\\";
        
        CURL curl = new CURL();
        curl.proxy("10.19.110.55", "8080");
        String resourceroot = Strings.get(params, "resourceroot",url);
        String filename = Strings.get(params, "filename",url.substring(url.indexOf("demo/")+5));
        String[] dirs = new String[]{"css/","js/","images/"};
        int at=0;
        if( resource.indexOf(".js") >=0 ){
            at = 1;
        }
        downloadResource(filepath+filename,filepath+filename+dirs[at],resourceroot,resource,curl);
        
    }
    
    @Override
    public void downloadPage(Map<String, Object> params) throws Exception {
        String url = Strings.get(params, "url");
        String filepath = "E:\\js-project\\ui\\";
        
        final CURL curl = new CURL();
        curl.proxy("10.19.110.55", "8080");
        final String resourceroot = Strings.get(params, "resourceroot",url);
        final String filename = Strings.get(params, "filename",url.substring(url.indexOf("demo/")+5));
        final String localroot = filepath;
        String stream = curl.curl(url);
        String[] regexs = new String[]{
                ".*?<link.*?href=(\"|')(?<url>[^\"']+?)(\"|').*?>.*",
                ".*?<script.*?src=(\"|')(?<url>[^\"']+?)(\"|').*?></script>.*", 
                ".*?<img.*?src=(\"|')(?<url>[^\"']+?)(\"|').*?>.*"
        };
        final String[] dirs = new String[]{"css/","js/","images/"};
        stream = Strings.replaceTxt(stream, regexs, "url",new Strings.LineCallback(){
            @Override
            public String replace(String line, String target,int regexat){
                //System.out.println(target);
                String dir = dirs[regexat];
                String name = downloadResource(localroot,localroot+dir,resourceroot,target,curl);
                return line.replace(target, dir+name);
            }
        });
        //System.out.println(stream);
        String indexfile = filepath+filename.substring(0,filename.length()-1)+".html";
        System.out.println(indexfile);
        FileUtil.writeFile(indexfile,stream);
    }
    
    @Override
    public void downloadPageResource(Map<String, Object> params) throws Exception {
        String url = Strings.get(params, "url");
        String resource = Strings.get(params, "resource");
        String filepath = "E:\\js-project\\ui\\";
        
        CURL curl = new CURL();
        curl.proxy("10.19.110.55", "8080");
        String resourceroot = Strings.get(params, "resourceroot",url);
        String[] dirs = new String[]{"css/","js/","images/"};
        int at=0;
        if( resource.indexOf(".js") >=0 ){
            at = 1;
        }
        downloadResource(filepath,filepath+dirs[at],resourceroot,resource,curl);
        
    }
    
}
